import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:love_app/common/su.dart';
import 'package:love_app/common/su_icon.dart';
import 'package:love_app/enum/agree.dart';
import 'package:love_app/model/community_model.dart' as CTYModel;
import 'package:love_app/model/community_model.dart';
import 'package:love_app/pages/community/null_item.dart';
import 'package:love_app/providers/search_provider.dart';
import 'package:love_app/providers/share_provider.dart';
import 'package:love_app/routes/application.dart';
import 'package:love_app/routes/routes.dart';
import 'package:love_app/service/community_api.dart';
import 'package:love_app/style/space_header.dart.dart';
import 'package:provider/provider.dart';

// 搜索结果页面
class SearchData extends StatefulWidget {
  final String search;

  const SearchData({Key key, this.search}) : super(key: key);

  @override
  _SearchDataState createState() => _SearchDataState();
}

class _SearchDataState extends State<SearchData> {
  ShareProvider _shareProvider;
  SearchProvider _searchProvider; // 搜索页面共享数据
  ScrollController _scrollController; // 滚动条监听控制器
  String _search;
  // CTYModel.CommunityModel _communityModel; // 搜索的数据
  EasyRefreshController _easyRefreshController; // 加载控制器

  @override
  void initState() {
    super.initState();
    _easyRefreshController = EasyRefreshController();
    _search = widget.search;
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _shareProvider = Provider.of<ShareProvider>(context, listen: false);
    _searchProvider = Provider.of<SearchProvider>(context, listen: false);
    if(_search != _searchProvider.searchData && _searchProvider.searchData != ""){
      _searchProvider.clean();
    }
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
    _easyRefreshController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    _addlistenOffset();
    return Scaffold(
      body: _body(),
    );
  }

  // 滚动条监听初始化
  void _addlistenOffset() {
    _scrollController = ScrollController(initialScrollOffset: _searchProvider.offset);
    _scrollController.addListener(() {
      _searchProvider.offset = _scrollController.offset;
    });
  }

  Widget _body() {
    return Container(
      child: EasyRefresh.custom(
        header: SpaceHeader(),
        firstRefresh: _searchProvider.isFirst,
        scrollController: _scrollController,
        controller: _easyRefreshController,
        bottomBouncing: true,
        enableControlFinishLoad: true,
        onLoad: () async {
          await _onLoad();
          setState(() {});
        },
        onRefresh: () async {
          _searchProvider.isFirst = false;
          await _onLoad();
          setState(() {});
        },
        slivers: <Widget>[
          _slivers(),
        ],
      ),
    );
  }

  Widget _slivers() {
    List<CTYModel.Data> data = _searchProvider.getAllItem();
    if (data.length == 0) {
      return SliverList(
        delegate: SliverChildListDelegate(
          [
            NullItem(),
          ],
        ),
      );
    }

    return SliverList(
      delegate: SliverChildBuilderDelegate(
        (context, index) {
          CTYModel.Data item = data[index];
          return _buildItem(item);
        },
        childCount: data.length,
      ),
    );
  }

  // 加载数据
  Future<void> _onLoad() async {
    CommunityModel model = await CommunityApi().getCommunitySearch(
        _shareProvider.token, _search,
        page: _searchProvider.page);
    try {
      if (model != null) {
        model.data.forEach((item) {
          _searchProvider.setAllItem(item.id, item);
        });
        _searchProvider.page ++;
        _easyRefreshController.finishLoad(success: true, noMore: false);
      }else{
        _searchProvider.isEndPage = true;
        _easyRefreshController.finishLoad(success: true, noMore: true);
      }
    } catch (e) {
      _easyRefreshController.finishLoad(success: true, noMore: false);
    }
  }

  // 构造每一个搜索结果
  Widget _buildItem(CTYModel.Data item) {
    Widget itemWidget = item.pictures.isEmpty == true
        ? _everyItemNoPic(item)
        : _everyItemHasPic(item);
    return Container(
      color: Colors.white,
      margin: EdgeInsets.only(
        bottom: Su().h(14),
      ),
      child: InkWell(
        child: itemWidget,
        onTap: () {
          Application.router.navigateTo(context,
              "/detailsPage?itemId=${item.id}&providerType=searchProvider");
        },
      ),
    );
  }

  // 每一个内容（内容中不包含图片的）
  Widget _everyItemNoPic(CTYModel.Data item) {
    return Container(
      margin: EdgeInsets.only(
        left: Su().w(30),
        // right: Su().w(63),
      ),
      child: Column(
        children: <Widget>[
          _textWidget(item.content),
          _itemIcon(item),
        ],
      ),
    );
  }

  // 每一个内容（内容中包含图片的）
  Widget _everyItemHasPic(CTYModel.Data item) {
    return Container(
      margin: EdgeInsets.only(
        left: Su().w(30),
        right: Su().w(63),
      ),
      child: Column(
        children: <Widget>[
          _textWidget(item.content),
          _itemPic(item.pictures),
          _itemIcon(item),
        ],
      ),
    );
  }

  // 每一项的文字
  Widget _textWidget(String text) {
    return Container(
      alignment: Alignment.centerLeft,
      padding: EdgeInsets.only(
        top: Su().h(19),
      ),
      child: _itemText(text.toString()),
    );
  }

  // 文字中第一个包含搜索内容的自己高亮
  Widget _itemText(String text) {
    // 查询第一个出现的下标位置
    int index = text.indexOf(_search);
    String firstText = text.substring(0, index);
    String lastText = text.substring(index + _search.length);
    return Text.rich(TextSpan(
        text: firstText,
        style: Su().textStyle(Color.fromRGBO(38, 38, 38, 1), 28),
        children: [
          TextSpan(
            text: _search,
            style: Su().textStyle(Color.fromRGBO(234, 52, 37, 1), 28),
          ),
          TextSpan(
            text: lastText,
            style: Su().textStyle(Color.fromRGBO(38, 38, 38, 1), 28),
          ),
        ]));
  }

  // 底部的点赞和评论
  Widget _itemIcon(CTYModel.Data item) {
    return Container(
      margin: EdgeInsets.only(
        bottom: Su().h(16),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Expanded(
            child: _agreeIcon(item.agree, item.isAgree),
          ),
          Expanded(
            child: _collectionsIcon(item.collections),
          ),
        ],
      ),
    );
  }

  // 点赞的Icon
  Widget _agreeIcon(int agreeNum, int isAgree) {
    Agree agreeType = IntToAgree.toAgree(isAgree);
    Color incnColor = agreeType == Agree.hasAgree
        ? Colors.red
        : Color.fromRGBO(179, 179, 179, 1);
    return Container(
      child: Row(
        children: <Widget>[
          Icon(
            Icons.favorite,
            color: incnColor,
            size: Su().w(25),
          ),
          Container(
            padding: EdgeInsets.only(
              left: Su().w(10),
            ),
            child: Text("$agreeNum人羡慕"),
          ),
        ],
      ),
    );
  }

  // 评论的Icon
  Widget _collectionsIcon(int collectionsNum) {
    return Container(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          Icon(
            SuIcon.collections,
            color: Color.fromRGBO(179, 179, 179, 1),
            size: Su().w(25),
          ),
          Container(
            padding: EdgeInsets.only(
              left: Su().w(10),
            ),
            child: Text("$collectionsNum"),
          ),
        ],
      ),
    );
  }

  // 图片部分
  Widget _itemPic(List<CTYModel.Pictures> pics) {
    List<CTYModel.Pictures> newPics = [];
    if (pics.length > 3) {
      newPics.add(pics[0]);
      newPics.add(pics[1]);
      newPics.add(pics[2]);
    } else {
      newPics = pics;
    }
    List<Widget> listWidget = [];
    newPics.forEach((item) {
      Widget pic = Container(
        padding: EdgeInsets.only(
          right: Su().w(12),
        ),
        child: Image.network(
          item.thumbnail,
          width: Su().w(205.8),
          height: Su().w(210.8),
          fit: BoxFit.cover,
        ),
      );
      listWidget.add(pic);
    });
    return Container(
      margin: EdgeInsets.only(
        top: Su().h(20),
        bottom: Su().h(20),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: listWidget,
      ),
    );
  }
}
